<template>
  <div class="container">
    <!-- 一周大事的具体内容 -->
    <div class="weekly-content" v-loading="loading">
      <el-form v-if="eventData?.content || showForm" ref="formRef" :model="eventData">
        <el-form-item>
          <Editor
            v-model="eventData.content"
            type="textarea"
            :rows="6"
            :readonly="!isWeek"
            placeholder="请输入本周大事记录"
          />
        </el-form-item>
        <el-form-item v-if="isWeek">
          <el-button type="primary" @click="saveEvent">保存</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>

      <el-empty v-else-if="!loading" description="暂无大事记录">
        <el-button v-if="isWeek" type="primary" @click="showForm = true">新增记录</el-button>
      </el-empty>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ClassEventApi, ClassEvent } from '@/api/school/classAffairs/event'
import dayjs from 'dayjs';
import isoWeek from 'dayjs/plugin/isoWeek';
dayjs.extend(isoWeek);
const route = useRoute()
const formRef = ref()
const emit = defineEmits(['refresh'])
const props = defineProps({
  date: {
    type: String,
    default: ''
  },
  isWeek: {
    type: Boolean,
    default: true
  }
})
const showForm = ref(false)
// 计算周一日期
const weeklyFirstDay = computed(() => {
  if (!props.date) return ''
  const currentDate = dayjs(props.date)
  const monday = currentDate.isoWeekday(1) // 获取周一
  return monday
})

// 事件数据
const eventData: any = ref({
  content: ''
})
const loading = ref(false)

// 获取一周大事数据
const fetchWeeklyEvent = async () => {
  if (!weeklyFirstDay.value) return
  loading.value = true
  try {
    // 根据接口文档，通过查询接口获取一周大事
    const data: any = await ClassEventApi.getClassEvent({
      classId: route.query.id,
      weekDateStart: weeklyFirstDay.value.format('YYYY-MM-DD')
    })
    eventData.value = data || {
      content: ''
    }
  } catch (error) {
    console.error('获取一周大事失败', error)
    eventData.value = null
  } finally {
    loading.value = false
  }
}

// 保存事件记录
const saveEvent = async () => {
  if (!eventData.value) return

  try {
    const newEventData = {
      classId: Number(route.query.id),
      weekDateStart: weeklyFirstDay.value.valueOf(),
      content: eventData.value.content
    } as ClassEvent
    if (eventData.value.id) {
      // 更新已存在的记录
      newEventData.id = eventData.value.id
      await ClassEventApi.updateClassEvent(newEventData)
      ElMessage.success('更新成功')
    } else {
      // 创建新记录
      await ClassEventApi.createClassEvent(newEventData)
      ElMessage.success('创建成功')
    }
    emit('refresh')
    fetchWeeklyEvent() // 重新获取数据
  } catch (error) {
    console.error('保存失败', error)
    ElMessage.error('保存失败')
  }
}

// 重置表单
const resetForm = () => {
  fetchWeeklyEvent()
}

// 监听日期变化，重新获取数据
watch(
  () => props.date,
  () => {
    fetchWeeklyEvent()
  },
  {
    immediate: true
  }
)
</script>

<style lang="scss" scoped>
.container {
  padding: 20px;
}

.weekly-content {
  margin-top: 20px;
}
</style>
